<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\Category as CategoryModel;
use fast\Tree;

/**
 * 分类管理
 *
 * @icon   fa fa-list dd
 * @remark 用于管理网站的所有分类,分类可进行无限级分类,分类类型请在常规管理->系统配置->字典配置中添加
 */
class Category extends Backend
{

    /**
     * @var \app\common\model\Category
     */
    protected $model = null;
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $categorylist = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('app\common\model\Category');

        $tree = Tree::instance();
        $tree->init(collection($this->model->where('is_deleted', '0')->where('status', '<>', '-1')->order('weigh desc,id desc')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata = [0 => ['type' => 'all', 'name' => __('None')]];
        foreach ($this->categorylist as $k => $v) {
            $categorydata[$v['id']] = $v;
        }
        $typeList = CategoryModel::getTypeList();
        $this->view->assign("flagList", $this->model->getFlagList());
        $this->view->assign("typeList", $typeList);
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("parentList", $categorydata);
        $this->assignconfig('typeList', $typeList);
    }



    public function getCategoryList()
    {
        $type = $this->request->param('type', '');

        if (empty($type)) {
            return json(['code' => 0, 'msg' => '类型参数不能为空']);
        }

        $this->model = model('app\common\model\Category');
        $categories = $this->model
            ->where('type', $type)
            ->where('is_deleted', 0)->where("status", 'normal')
            ->select();
        $this->categorylist=$categories;
        return json($categories);
    }
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $search = $this->request->request("search");
            $type = $this->request->request("type");
            
            // 获取城市和学校过滤参数
            $city_id = $this->request->get("city_id");
            $school_id = $this->request->get("school_id");
            
            // 调试日志
            error_log("Category Index - city_id: $city_id, school_id: $school_id, type: $type, search: $search");

            //构造父类select列表选项数据
            $list = [];
            $this->getCategoryList();
            foreach ($this->categorylist as $k => $v) {
                $includeItem = false;
                
                // 首先检查搜索和类型条件
                if ($search) {
                    if ($v['type'] == $type && stripos($v['name'], $search) !== false || stripos($v['nickname'], $search) !== false) {
                        if ($type == "all" || $type == null) {
                            $includeItem = true;
                        } else {
                            $includeItem = true;
                        }
                    }
                } else {
                    if ($type == "all" || $type == null) {
                        $includeItem = true;
                    } elseif ($v['type'] == $type) {
                        $includeItem = true;
                    }
                }
                
                // 如果基本条件满足，再检查城市和学校过滤
                if ($includeItem) {
                    $cityMatch = true;
                    $schoolMatch = true;
                    
                    // 城市过滤
                    if (!empty($city_id)) {
                        if (isset($v['city_id'])) {
                            $cityMatch = ($v['city_id'] == $city_id);
                        } else {
                            // 如果分类没有city_id字段，可以考虑跳过或包含
                            $cityMatch = true;
                        }
                    } else if (isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 2) {
                        // 城市管理员权限控制
                        if (isset($v['city_id'])) {
                            $cityMatch = ($v['city_id'] == $_SESSION['think']['admin']['city_id']);
                        }
                    }
                    
                    // 学校过滤
                    if (!empty($school_id)) {
                        if (isset($v['school_id'])) {
                            $schoolMatch = ($v['school_id'] == $school_id);
                        } else {
                            // 如果分类没有school_id字段，可以考虑跳过或包含
                            $schoolMatch = true;
                        }
                    }
                    
                    // 只有城市和学校都匹配才包含该项
                    if ($cityMatch && $schoolMatch) {
                        if ($search) {
                            if ($type == "all" || $type == null) {
                                $list[] = $v;
                            } else {
                                $list[] = $v;
                            }
                        } else {
                            if ($type == "all" || $type == null) {
                                $list[] = $v;
                            } else {
                                $list[] = $v;
                            }
                        }
                    }
                }
            }

            $total = count($list);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($params['pid'] != $row['pid']) {
                    $childrenIds = Tree::instance()->init(collection(\app\common\model\Category::select())->toArray())->getChildrenIds($row['id'], true);
                    if (in_array($params['pid'], $childrenIds)) {
                        $this->error(__('Can not change the parent to child or itself'));
                    }
                }

                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 获取指定类型的分类列表
     */
    public function typelist()
    {
        $type = $this->request->param('type', '');

        if (empty($type)) {
            $this->error('类型参数不能为空');
        }

        $list = $this->model
            ->where('type', $type)
            ->where('is_deleted', 0)
            ->where("status", 'in', ['1', 'normal'])
            ->field('id,name,type,flag,pid,weigh')
            ->order('weigh desc,id desc')
            ->select();
        $list = collection($list)->toArray();
        $this->success('获取成功', '', $list);
    }

    public function lists()
    {
        $type = $this->request->param('type', '');

        if (empty($type)) {
            $this->error('类型参数不能为空');
        }

        $list = $this->model
            ->where('type', $type)
            ->where('is_deleted', 0)
            ->where("status", 'in', ['1', 'normal'])
            ->field('id,name,type,flag,pid,weigh,image_width,image_height')
            ->order('weigh desc,id desc')
            ->select();
        $list = collection($list)->toArray();
        $this->success('获取成功', '', $list);
    }

    /**
     * Selectpage搜索
     *
     * @internal
     */
    public function selectpage()
    {
        return parent::selectpage();
    }
}
